package com.mina.handler;

import com.mina.entity.MinaMsg;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import java.util.ArrayList;
import java.util.List;

/**
 * 服务端消息处理器
 *
 * @author sam
 */
public class MinaServerHandler extends IoHandlerAdapter {


    public static List<IoSession> list = new ArrayList<>();

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        list.add(session);
        super.sessionCreated(session);
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        super.sessionOpened(session);
        System.out.println("client connected -> " + session.getRemoteAddress());
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        super.sessionClosed(session);
        System.out.println("client disconnected -> " + session.getRemoteAddress());
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        super.messageReceived(session, message);
        MinaMsg msg = (MinaMsg) message;
        System.out.println("received message from client:" + msg);
//        session.write("echo" + msg);
        /**转发消息**/
        for (IoSession i : list) {
            if (!session.equals(i)) i.write(msg.getFrom() + " says: " + msg.getInfo());
        }
    }
}
